﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;
using PopupControl;

namespace ManageTicket.Ticket
{
    public partial class frmInvoice : frmBase
    {
        #region Contructor
        public frmInvoice()
        {
            InitializeComponent();

            popupToolTip = new Popup(uctrlPopupVoucher = new ManageTicket.Library.Control.PopupVoucher1());
            popupToolTip.AutoClose = false;
            popupToolTip.FocusOnOpen = false;
            popupToolTip.ShowingAnimation = popupToolTip.HidingAnimation = PopupAnimations.LeftToRight | PopupAnimations.Slide;
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();
        private Business.Invoice boInvoice = new Business.Invoice();
        private Business.Voucher boVoucher = new Business.Voucher();
        private Business.VoucherHistory boVoucherHistory = new Business.VoucherHistory();
        private Business.Employee boEmployee = new Business.Employee();
        private Business.Customer boCustomer = new Business.Customer();
        private Business.CodeType boCodeType = new Business.CodeType();
        string sModel = ""; //Store AND or UPDATE status
        private const string ADD_MODEL = "ADD";
        private const string UPDATE_MODEL = "UPDATE";
        private string VOUCHER_NO = "";
        Popup popupToolTip;
        Library.Control.PopupVoucher1 uctrlPopupVoucher;
        #endregion

        #region Event
        private void frmInvoice_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật hóa đơn";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, "FORM_03");

            GetListType();
            clsCommonFunc.GetListCodeType(cboCurrency, "CUR");
            clsCommonFunc.GetListCodeType(cboPaymentForm, "PF"); 
            clsCommonFunc.GetListCodeType(cboBank, "BANK");
            cboKindOfVoucher.SelectedIndex = -1;
            cboKindOfInvoice.SelectedIndex = -1;
            cboCurrency.SelectedIndex = -1;
            cboPaymentForm.SelectedIndex = -1;
            cboPaymentForm_SelectedIndexChanged(null, null);
            
            objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });

            objMethod.en_dis_control(new Control[] { lvwVoucher, grpListInvoice }, new Control[] { grpDetail });
            LoadStatusOnce();
            LoadStatus(false, false, false, false, false, true, false);
            GetVoucher();
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ArrayList arrResult = new ArrayList();
                if (objMethod.IsDouble(txtSearch.Text))
                {
                    DataObjects.Voucher oVou = boVoucher.GetObjectByPK(txtSearch.Text);
                    if (oVou != null)
                    {
                        arrResult.Add(oVou);
                    }
                }
                else
                {
                    ArrayList arr1 = boVoucher.GetListQuickSearch(txtSearch.Text);
                    if (arr1 != null)
                    {
                        if (arr1.Count == 1)
                        {
                            arrResult.Add(arr1[0]);
                        }
                        else if (arr1.Count > 1)
                        {
                            frmQuickSearchVoucher frmQS = new frmQuickSearchVoucher(arr1);
                            frmQS.ShowDialog();
                            foreach (DataObjects.Voucher oVou in frmQS.arrResult)
                            {
                                arrResult.Add(oVou);
                            }
                        }
                    }
                }

                ListViewItem item;
                int firstItem = 0;
                DataObjects.Customer oCus;
                DataObjects.Voucher oVou1;

                foreach (DataObjects.Voucher oVou_ in arrResult)
                {
                    oVou1 = boVoucher.GetObjectByPK(oVou_.VoucherNo);

                    if (!IsInListViewVoucher(oVou1))
                    {
                        item = new ListViewItem();
                        item.Text = oVou1.VoucherNo;
                        //oCus = boCustomer.GetObjectByPK(oVou1.CustomerId);
                        //if (oCus != null)
                        //    item.SubItems.Add(oCus.CustomerName);
                        //else
                        //    item.SubItems.Add("");
                        //item.SubItems.Add(oVou1.DateOfVoucher.Value.ToString("dd/MM/yyyy hh:mm tt"));
                        //item.SubItems.Add(objMethod.FormatCurency(oVou1.BuySumVnd.ToString()));
                        //item.SubItems.Add(objMethod.FormatCurency(oVou1.SaleSumVnd.ToString()));
                        lvwVoucher.Items.Add(item);

                        if (firstItem == 0)
                        {
                            item.Selected = true;
                        }
                        firstItem++;
                    }
                }
            }
        }

        private void lvwVoucher_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwVoucher.SelectedItems.Count > 0)
            {
                VOUCHER_NO = lvwVoucher.SelectedItems[0].Text;
                objMethod.en_dis_control(new Control[] { grpListInvoice }, new Control[] { grpDetail });
                LoadStatus(true, false, false, false, false, true, false);
                GetListInvoice(VOUCHER_NO);
            }
            else
            {
                VOUCHER_NO = "";
                objMethod.en_dis_control(new Control[] { }, new Control[] { grpListInvoice, grpDetail });
                LoadStatus(false, false, false, false, false, true, false);
                lvwInvoice_SelectedIndexChanged(null, null);
            }
        }

        private void lvwVoucher_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {
            if (e.Item.Text != "")
            {
                DataObjects.Voucher oVou = boVoucher.GetObjectByPK(e.Item.Text);
                DataObjects.Customer oCus;
                if (oVou != null)
                {
                    uctrlPopupVoucher.lblVoucherNo.Text = "Số phiếu: " + oVou.VoucherNo;
                    uctrlPopupVoucher.lblDateOfVoucher.Text = "Ngày lập: " + oVou.DateOfVoucher.Value.ToString("dd/MM/yyyy hh:mm tt");
                    uctrlPopupVoucher.lblCustomerId.Text = "Mã khách hàng: " + oVou.CustomerId;
                    oCus = boCustomer.GetObjectByPK(oVou.CustomerId);
                    if (oCus != null)
                        uctrlPopupVoucher.lblCustomerName.Text = "Khách hàng: " + oCus.CustomerName;
                    uctrlPopupVoucher.lblPersonRepresent.Text = "Liên hệ: " + oVou.CustomerPersonRepresent;

                    //buy
                    uctrlPopupVoucher.lblBuyTotal.Text = objMethod.FormatCurency(oVou.BuyTotal.ToString());
                    uctrlPopupVoucher.lblBuyVatPercent.Text = oVou.BuyVatPercent.ToString();
                    uctrlPopupVoucher.lblBuyVat.Text = objMethod.FormatCurency(oVou.BuyVat.ToString());
                    uctrlPopupVoucher.lblBuySum.Text = objMethod.FormatCurency(oVou.BuySum.ToString());
                    uctrlPopupVoucher.lblBuyCurrency.Text = GetCodeTypeName(oVou.BuyCurrency);
                    uctrlPopupVoucher.lblBuyExchange.Text = objMethod.FormatCurency(oVou.BuyExchange.ToString());
                    uctrlPopupVoucher.lblBuySumVnd.Text = objMethod.FormatCurency(oVou.BuySumVnd.ToString());

                    //sale
                    uctrlPopupVoucher.lblSaleTotal.Text = objMethod.FormatCurency(oVou.SaleTotal.ToString());
                    uctrlPopupVoucher.lblSaleVatPercent.Text = oVou.SaleVatPercent.ToString();
                    uctrlPopupVoucher.lblSaleVat.Text = objMethod.FormatCurency(oVou.SaleVat.ToString());
                    uctrlPopupVoucher.lblSaleSum.Text = objMethod.FormatCurency(oVou.SaleSum.ToString());
                    uctrlPopupVoucher.lblSaleCurrency.Text = GetCodeTypeName(oVou.SaleCurrency);
                    uctrlPopupVoucher.lblSaleExchange.Text = objMethod.FormatCurency(oVou.SaleExchange.ToString());
                    uctrlPopupVoucher.lblSaleSumVnd.Text = objMethod.FormatCurency(oVou.SaleSumVnd.ToString());
                    uctrlPopupVoucher.lblSaleCommission.Text = "Hoa hồng VND: " + objMethod.FormatCurency(oVou.SaleCommission.ToString());

                    Rectangle rect = new Rectangle(MousePosition.X, -100, 300, 130);// lvwVoucher.GetCellDisplayRectangle(0, 0, true);
                    popupToolTip.Show(lvwVoucher, rect);
                }
            }
        }

        private void lvwVoucher_MouseLeave(object sender, EventArgs e)
        {
            popupToolTip.Close();
        }

        private void lvwInvoice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwInvoice.SelectedItems.Count > 0)
            {
                FillData(lvwInvoice.SelectedItems[0].Text);
                LoadStatus(true, true, true, false, false, true, true);
            }
            else
            {
                LoadStatus(true, false, false, false, false, true, false);
                objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
                cboKindOfVoucher.SelectedIndex = -1;
                cboKindOfInvoice.SelectedIndex = -1;
                cboCurrency.SelectedIndex = -1;
                cboPaymentForm.SelectedIndex = -1;
                cboPaymentForm_SelectedIndexChanged(null, null);
            }
        }

        private void dtpDateOfInvoice_ValueChanged(object sender, EventArgs e)
        {
            if (sModel == ADD_MODEL)
                txtInvoiceNo.Text = "I" + dtpDateOfInvoice.Value.ToString("yyyyMMdd") + clsCommonFunc.RuleNumber5(boInvoice.GetMaxID("I" + dtpDateOfInvoice.Value.ToString("yyyyMMdd")) + 1);
        }

        private void cboKindOfVoucher_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sModel == ADD_MODEL || sModel == UPDATE_MODEL)
            {
                if (cboKindOfVoucher.SelectedValue != null)
                {
                    if (cboKindOfVoucher.Text.Contains("Thu"))
                        cboKindOfInvoice.Text = "Thu";
                    else if (cboKindOfVoucher.Text.Contains("Chi"))
                        cboKindOfInvoice.Text = "Chi";
                    else
                        cboKindOfInvoice.Text = "";
                }
            }
            else
                cboKindOfInvoice.Text = "";
        }

        private void cboCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboCurrency.SelectedIndex >= 0)
            {
                if (cboCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                {
                    txtExchange.Text = "1";
                    Calculate();
                }
            }
        }

        private void cboPaymentForm_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboPaymentForm.SelectedIndex != -1)
                {
                    if (cboPaymentForm.SelectedValue.ToString() == "PF_1")
                    {
                        cboBank.SelectedIndex = -1;
                        cboBank.Enabled = false;
                    }
                    else
                    {
                        cboBank.Enabled = true;
                        if (cboBank.Items.Count > 0)
                        {
                            cboBank.SelectedIndex = 0;
                            cboBank.Focus();
                        }
                    }
                }
                else
                {
                    cboBank.SelectedIndex = -1;
                    cboBank.Enabled = false;
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }

        private void txtMoney_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtMoney.Text);
        }

        private void txtMoney_Leave(object sender, EventArgs e)
        {
            Calculate();
        }

        private void txtExchange_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtExchange.Text);
        }

        private void txtExchange_Leave(object sender, EventArgs e)
        {
            Calculate();
        }

        private void txtCashierId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtCashierId.Text);
                if (oCus != null)
                {
                    txtCashierName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtCashierName.Focus();
                }
            }
        }

        private void txtReceiverId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtReceiverId.Text);
                if (oCus != null)
                {
                    txtReceiverName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtReceiverName.Focus();
                }
            }
        }
         
        #endregion

        #region Execute
        public override void Add()
        {
            if (lvwVoucher.SelectedItems.Count <= 0)
                return;
            objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
            LoadStatus(false, false, false, true, true, false, false);
            objMethod.en_dis_control(new Control[] { grpDetail, txtInvoiceNo }, new Control[] {lvwVoucher, grpListInvoice });
            
            dtpDateOfInvoice.Value = DateTime.Now;
            txtInvoiceNo.Text = dtpDateOfInvoice.Value.ToString("yyMMdd") + clsCommonFunc.RuleNumber5(boInvoice.GetMaxID(dtpDateOfInvoice.Value.ToString("yyMMdd")) + 1);

            if (cboPaymentForm.SelectedIndex >= 0)
                cboPaymentForm.SelectedIndex = 0;
            cboPaymentForm_SelectedIndexChanged(null, null);

            txtCashierId.Text = frmMain.CurrentUser.EmployeeId;
            DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtCashierId.Text);
            if (oCus != null)
            {
                txtCashierName.Text = oCus.LastName + " " + oCus.FirstName;
            }
            
            dtpDateOfInvoice.Focus();
            sModel = ADD_MODEL;
        }

        public override void Edit()
        {
            if (lvwInvoice.SelectedItems.Count <= 0)
                return;
            LoadStatus(false, false, false, true, true, false, false);
            objMethod.en_dis_control(new Control[] { grpDetail, txtInvoiceNo }, new Control[] { lvwVoucher, grpListInvoice, txtInvoiceNo });
            
            dtpDateOfInvoice.Focus();
            sModel = UPDATE_MODEL;
        }

        public override void Delete()
        {
            try
            {
                if (txtInvoiceNo.Text == "")
                    return;

                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Check Existing in table
                    //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                    //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return;
                    //}

                    //delete
                    boVoucherHistory.DeleteByVoucherNoInvoiceNo(VOUCHER_NO, txtInvoiceNo.Text);
                    boInvoice.DeleteByPK(txtInvoiceNo.Text);
                    
                    MessageBox.Show("Xóa hóa đơn thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Cancel();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Cancel()
        {
            objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
            lvwVoucher_SelectedIndexChanged(null, null);
            if (lvwInvoice.Items.Count > 0)
            {
                lvwInvoice.Items[0].Selected = true;
            }
            else
            {
                LoadStatus(true, false, false, false, false, true, false);
            }
            objMethod.en_dis_control(new Control[] { lvwVoucher, grpListInvoice  }, new Control[] { grpDetail });

            sModel = "";
        }

        public override void Save()
        {
            if (CheckValid())
            {
                try
                {
                    DataObjects.Invoice oInvoice = new DataObjects.Invoice();
                    oInvoice.InvoiceNo = txtInvoiceNo.Text;
                    oInvoice.VoucherNo = VOUCHER_NO;
                    oInvoice.DateOfInvoice = dtpDateOfInvoice.Value;
                    oInvoice.KindOfVoucher = cboKindOfVoucher.SelectedValue.ToString();
                    oInvoice.KindOfInvoice = cboKindOfInvoice.Text;
                    oInvoice.Money = txtMoney.Text != "" ? double.Parse(txtMoney.Text) : 0;
                    oInvoice.Currency = cboCurrency.SelectedValue.ToString();
                    oInvoice.Exchange = txtExchange.Text != "" ? double.Parse(txtExchange.Text) : 0;
                    oInvoice.PaymentForm = cboPaymentForm.SelectedValue.ToString();
                    if (cboBank.SelectedIndex >= 0)
                        oInvoice.Bank = cboBank.SelectedValue.ToString();
                    oInvoice.Cashier = txtCashierId.Text;
                    oInvoice.Receiver = txtReceiverId.Text;
                    oInvoice.Remark = txtRemark.Text;

                    if (sModel == ADD_MODEL)
                    {
                        //insert
                        if (CheckIsExist(oInvoice.InvoiceNo))
                        {
                            MessageBox.Show("Số hóa đơn đã tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtInvoiceNo.Focus();
                            return;
                        }
                        boInvoice.Insert(oInvoice);
                        InsertVoucherHistory(oInvoice);
                    }
                    else if (sModel == UPDATE_MODEL)
                    {
                        boInvoice.Update(oInvoice);
                        UpdateVoucherHistory(oInvoice);
                    }
                    MessageBox.Show("Cập nhật hóa đơn thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Cancel();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật hóa đơn.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public override void Find()
        {
            frmFindTicket frmFind = new frmFindTicket();
            frmFind.ShowDialog();

            //ArrayList arrResult = frmFind.arrResult;
            GetVoucher();
        }

        public override void Function()
        {
            MsgBox mbox = new MsgBox();
            mbox.ShowDialog();

            if (mbox.PARTNER == "Customer")
            {
                frmInvoiceSeriesCustomer frm = new frmInvoiceSeriesCustomer();
                frm.MdiParent = this.ParentForm;
                frm.Show();
            }
            else if (mbox.PARTNER == "Provider")
            {
                frmInvoiceSeries frm = new frmInvoiceSeries();
                frm.MdiParent = this.ParentForm;
                frm.Show();
            }
            else if (mbox.PARTNER == "Commission")
            {
                frmInvoiceSeriesCommission frm = new frmInvoiceSeriesCommission();
                frm.MdiParent = this.ParentForm;
                frm.Show();
            }
        }

        public override void Print()
        {
            if (txtInvoiceNo.Text.Trim() != "")
            {
                frmPrintInvoice frm = new frmPrintInvoice(txtInvoiceNo.Text);
                frm.ShowDialog();
            }
        }
        #endregion

        #region Method
        public void GetListType()
        {
            try
            {
                Business.CodeType boCodeType = new Business.CodeType();
                ArrayList arr = boCodeType.GetListCodeTypeByGroup("VSTATUS", "VSTATUS_1");
                cboKindOfVoucher.DataSource = arr;
                cboKindOfVoucher.ValueMember = "CodeTypeId";
                cboKindOfVoucher.DisplayMember = "CodeTypeName";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadStatusOnce()
        {
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;
            //exeCtrl.btnPrint.Enabled = false;

            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
            //exeCtrl.btnPrint.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blEdit, bool blDelete, bool blCancel, bool blSave, bool blFind, bool blPrint)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnEdit.Enabled = blEdit & bEdit;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnCancel.Enabled = blCancel & bCancel;
            exeCtrl.btnSave.Enabled = blSave & bSave;
            exeCtrl.btnFind.Enabled = blFind & bFind;
            exeCtrl.btnPrint.Enabled = blPrint & bPrint;

            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnEdit.ButtonColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = exeCtrl.btnFind.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = exeCtrl.btnPrint.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnEdit.ForeColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = exeCtrl.btnFind.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = exeCtrl.btnPrint.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }
 
        private bool IsInListViewVoucher(DataObjects.Voucher oVou)
        {
            foreach (ListViewItem item in lvwVoucher.Items)
            {
                if (item.Text == oVou.VoucherNo)
                {
                    return true;
                }
            }
            return false;
        }

        private void GetVoucher()
        {
            ArrayList arrResult = ManageTicket.Library.Common.CommonList.ListVoucher;
            ListViewItem item;
            int firstItem = 0;
            DataObjects.Customer oCus;
            DataObjects.Voucher oVou1;

            if (arrResult != null)
            {
                foreach (DataObjects.Voucher oVou_ in arrResult)
                {
                    oVou1 = boVoucher.GetObjectByPK(oVou_.VoucherNo);

                    if (!IsInListViewVoucher(oVou1))
                    {
                        item = new ListViewItem();
                        item.Text = oVou1.VoucherNo;
                        //oCus = boCustomer.GetObjectByPK(oVou1.CustomerId);
                        //if (oCus != null)
                        //    item.SubItems.Add(oCus.CustomerName);
                        //else
                        //    item.SubItems.Add("");
                        //item.SubItems.Add(oVou1.DateOfVoucher.Value.ToString("dd/MM/yyyy hh:mm tt"));
                        //item.SubItems.Add(objMethod.FormatCurency(oVou1.BuySumVnd.ToString()));
                        //item.SubItems.Add(objMethod.FormatCurency(oVou1.SaleSumVnd.ToString()));
                        lvwVoucher.Items.Add(item);

                        if (firstItem == 0)
                        {
                            item.Selected = true;
                        }
                        firstItem++;
                    }
                }
            }
        }

        private void GetListInvoice(string voucher_no)
        {
            try
            {
                lvwInvoice.Items.Clear();
                ArrayList arr = boInvoice.GetListByVoucherNo(voucher_no);
                if (arr.Count > 0)
                {
                    ListViewItem item;
                    DataObjects.CodeType oCodeType;
                    foreach (DataObjects.Invoice oInv in arr)
                    {
                        item = new ListViewItem();
                        item.Text = oInv.InvoiceNo;
                        item.SubItems.Add(oInv.DateOfInvoice.Value.ToString("dd/MM/yyyy hh:mm tt"));
                        oCodeType = boCodeType.GetObjectByPK(oInv.KindOfVoucher);
                        if (oCodeType != null)
                            item.SubItems.Add(oCodeType.CodeTypeName);
                        else
                            item.SubItems.Add("");
                        oCodeType = null;
                        item.SubItems.Add(oInv.KindOfInvoice);
                        item.SubItems.Add(objMethod.FormatCurency(oInv.Money.ToString()));
                        oCodeType = boCodeType.GetObjectByPK(oInv.Currency);
                        if (oCodeType != null)
                            item.SubItems.Add(oCodeType.CodeTypeName);
                        else
                            item.SubItems.Add("");
                        oCodeType = null;
                        oCodeType = boCodeType.GetObjectByPK(oInv.PaymentForm);
                        if (oCodeType != null)
                            item.SubItems.Add(oCodeType.CodeTypeName);
                        else
                            item.SubItems.Add("");
                        oCodeType = null;
                        item.SubItems.Add(oInv.Remark);
                        lvwInvoice.Items.Add(item);
                    }

                    if (lvwInvoice.Items.Count > 0)
                    {
                        lvwInvoice.Items[0].Selected = true;
                    }
                }
                else
                {
                    objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
                    cboKindOfVoucher.SelectedIndex = -1;
                    cboKindOfInvoice.SelectedIndex = -1;
                    cboCurrency.SelectedIndex = -1;
                    cboPaymentForm.SelectedIndex = -1;
                    cboPaymentForm_SelectedIndexChanged(null, null);
                }
            }
            
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Calculate()
        {
            try
            {
                double money = 0;
                double exchange = 0;
                double moneyvnd = 0;

                try { money = txtMoney.Text != "" ? double.Parse(txtMoney.Text) : 0; }
                catch { }

                try
                {
                    if (cboCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                    {
                        exchange = 1;
                    }
                    else
                    {
                        exchange = txtExchange.Text != "" ? double.Parse(txtExchange.Text) : 0;
                    }
                }
                catch { }
                moneyvnd = money * exchange;

                //display
                txtMoney.Text = objMethod.FormatCurency(money.ToString());
                txtExchange.Text = objMethod.FormatCurency(exchange.ToString());
                txtMoneyVND.Text = objMethod.FormatCurency(moneyvnd.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillData(string invoice_no)
        {
            DataObjects.Invoice oInv = boInvoice.GetObjectByPK(invoice_no);
            DataObjects.Employee oEmp;
            if (oInv != null)
            {
                txtInvoiceNo.Text = oInv.InvoiceNo;
                dtpDateOfInvoice.Value = oInv.DateOfInvoice.Value;
                cboKindOfVoucher.SelectedValue = oInv.KindOfVoucher;
                cboKindOfInvoice.Text = oInv.KindOfInvoice;
                txtMoney.Text = objMethod.FormatCurency(oInv.Money.ToString());
                cboCurrency.SelectedValue = oInv.Currency;
                txtExchange.Text = objMethod.FormatCurency(oInv.Exchange.ToString());
                Calculate();
                cboPaymentForm.SelectedValue = oInv.PaymentForm;
                if (oInv.Bank != null && oInv.Bank != "")
                    cboBank.SelectedValue = oInv.Bank;
                else
                    cboBank.SelectedIndex = -1;
                txtCashierId.Text = oInv.Cashier;
                oEmp = boEmployee.GetObjectByPK(oInv.Cashier);
                if (oEmp != null)
                    txtCashierName.Text = oEmp.LastName + " " + oEmp.FirstName;
                txtReceiverId.Text = oInv.Receiver;
                oEmp = null;
                oEmp = boEmployee.GetObjectByPK(oInv.Receiver);
                if (oEmp != null)
                    txtReceiverName.Text = oEmp.LastName + " " + oEmp.FirstName;
                txtRemark.Text = oInv.Remark;
            }
        }

        private bool CheckValid()
        {
            if (txtInvoiceNo.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập số hóa đơn.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtInvoiceNo.Focus();
                return false;
            }
            else if (!objMethod.CheckSpecialCharacter(txtInvoiceNo.Text))
            {
                MessageBox.Show("Số hóa đơn không được nhập các ký tự đặc biệt.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtInvoiceNo.Focus();
                return false;
            }

            if (cboKindOfVoucher.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn loại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboKindOfVoucher.Focus();
                return false;
            }

            if (cboKindOfInvoice.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn thu/chi.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboKindOfInvoice.Focus();
                return false;
            }

            if (txtMoney.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập số tiền.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtMoney.Focus();
                return false;
            }

            if (cboCurrency.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn loại tiền tệ.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboCurrency.Focus();
                return false;
            }

            if (cboPaymentForm.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn hình thức thanh toán.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboPaymentForm.Focus();
                return false;
            }
            
            if (txtCashierId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn người lập.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCashierId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtCashierId.Text);
                if (oEmp == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtCashierId.Focus();
                    return false;
                }
            }

            if (txtReceiverId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn người nhận.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtReceiverId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtReceiverId.Text);
                if (oEmp == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtReceiverId.Focus();
                    return false;
                }
            }

            return true;
        }

        private bool CheckIsExist(string invoice_no)
        {
            DataObjects.Invoice oInvoice = boInvoice.GetObjectByPK(invoice_no);
            if (oInvoice != null)
            {
                return true;
            }
            return false;
        }

        private void InsertVoucherHistory(DataObjects.Invoice oInvoice)
        {
            //delete
            //boVoucherHistory.DeleteByVoucherNoInvoiceNo(oInvoice.VoucherNo, oInvoice.InvoiceNo);

            //insert
            DataObjects.VoucherHistory oVouHis = new DataObjects.VoucherHistory();
            oVouHis.VoucherNo = oInvoice.VoucherNo;
            oVouHis.InvoiceNo = oInvoice.InvoiceNo;
            oVouHis.DateCreate = oInvoice.DateOfInvoice;
            oVouHis.Status = oInvoice.KindOfVoucher;
            oVouHis.Remark = oInvoice.Remark;
            oVouHis.UserId = frmMain.CurrentUser.UserId;
            oVouHis.DateInput = DateTime.Now;
            if (oInvoice.Currency.ToUpper() == "CUR_1")
            {
                if (oInvoice.KindOfInvoice.ToUpper() == "THU")
                {
                    oVouHis.IncomingVnd = oInvoice.Money;
                }
                else if (oInvoice.KindOfInvoice.ToUpper() == "CHI")
                {
                    oVouHis.OutgoingVnd = oInvoice.Money;
                }
            }
            else if (oInvoice.Currency.ToUpper() == "CUR_2")
            {
                if (oInvoice.KindOfInvoice.ToUpper() == "THU")
                {
                    oVouHis.IncomingUsd = oInvoice.Money;
                }
                else if (oInvoice.KindOfInvoice.ToUpper() == "CHI")
                {
                    oVouHis.OutgoingUsd = oInvoice.Money;
                }
            }

            boVoucherHistory.Insert(oVouHis);
        }

        private void UpdateVoucherHistory(DataObjects.Invoice oInvoice)
        {
            ArrayList arr = boVoucherHistory.GetListByVoucherNoInvoiceNo(oInvoice.VoucherNo, oInvoice.InvoiceNo);
            foreach (DataObjects.VoucherHistory oVouHis in arr)
            {
                oVouHis.VoucherNo = oInvoice.VoucherNo;
                oVouHis.InvoiceNo = oInvoice.InvoiceNo;
                oVouHis.DateCreate = oInvoice.DateOfInvoice;
                oVouHis.Status = oInvoice.KindOfVoucher;
                oVouHis.Remark = oInvoice.Remark;
                oVouHis.UserId = frmMain.CurrentUser.UserId;
                oVouHis.DateInput = DateTime.Now;
                if (oInvoice.Currency.ToUpper() == "CUR_1")
                {
                    if (oInvoice.KindOfInvoice.ToUpper() == "THU")
                    {
                        oVouHis.IncomingVnd = oInvoice.Money;
                    }
                    else if (oInvoice.KindOfInvoice.ToUpper() == "CHI")
                    {
                        oVouHis.OutgoingVnd = oInvoice.Money;
                    }
                }
                else if (oInvoice.Currency.ToUpper() == "CUR_2")
                {
                    if (oInvoice.KindOfInvoice.ToUpper() == "THU")
                    {
                        oVouHis.IncomingUsd = oInvoice.Money;
                    }
                    else if (oInvoice.KindOfInvoice.ToUpper() == "CHI")
                    {
                        oVouHis.OutgoingUsd = oInvoice.Money;
                    }
                }

                //update
                boVoucherHistory.Update(oVouHis);
            }               
        }

        private string GetCodeTypeName(string Id)
        {
            Business.CodeType boCodeType = new Business.CodeType();
            DataObjects.CodeType oCodeType = boCodeType.GetObjectByPK(Id);
            if (oCodeType != null)
                return oCodeType.CodeTypeName;
            return "";
        }

        #endregion

        

        

        
   
    }
}
